package com.jueling.culture.service.impl;


import com.jueling.culture.core.service.TokenManageService;
import com.jueling.culture.dto.InitDto;
import com.jueling.culture.dto.TokenDto;
import com.jueling.culture.dto.req.LoginVO;
import com.jueling.culture.exception.FrontShowException;
import com.jueling.culture.model.UserAuthority;
import com.jueling.culture.model.UserInfo;
import com.jueling.culture.service.LoginService;
import com.jueling.culture.service.UserAuthorityService;
import com.jueling.culture.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author linp
 * @create 2022/2/10 14:52
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserAuthorityService userAuthorityService;
    @Autowired
    private TokenManageService tokenManageService;

    /**
     * 登录
     *
     * @param loginVO
     * @return
     */
    @Override
    public InitDto doLogin(LoginVO loginVO) {
        //加密密码
        String md5Password= UserInfo.getMD5Password(loginVO.getUserName(),loginVO.getPassword());
        //判断账号密码是否正确
        UserInfo userInfo = userInfoService.login(loginVO.getUserName(),md5Password);
        if(userInfo == null){
            throw new FrontShowException("账号密码错误！");
        }
        //获取用户权限集合
        List<UserAuthority> userAuthorityList = userAuthorityService.getUserAuthorityList(userInfo.getUserId());
        userInfo.setUserAuthority(userAuthorityList);
        UserInfo.currentUser.set(userInfo);
        TokenDto tokenDto= tokenManageService.createToken(userInfo);
        InitDto initDto = new InitDto();
        initDto.setUserAuthority(userAuthorityList);
        initDto.setName(userInfo.getName());
        initDto.setPhone(userInfo.getPhone());
        initDto.setUserId(userInfo.getUserId());
        initDto.setAccessToken(tokenDto.getAccessToken());
        initDto.setRoleId(userInfo.getRoleId());
        initDto.setUnderCustId(userInfo.getUnderCustId());
        return initDto;
    }
}
